import 'package:flutter/material.dart';
import '../../core/constants.dart';
import '../../core/routes.dart';
import '../../data/repositories/image_repository.dart';

/// 主页界面
class HomeScreen extends StatefulWidget {
  const HomeScreen({super.key});
  
  @override
  State<HomeScreen> createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> with TickerProviderStateMixin {
  final ImageRepository _imageRepository = ImageRepository();
  
  // 动画控制器
  late AnimationController _fadeController;
  late AnimationController _slideController;
  late Animation<double> _fadeAnimation;
  late Animation<Offset> _slideAnimation;
  
  // 选中的图片和难度
  String? _selectedImagePath;
  DifficultyLevel _selectedDifficulty = DifficultyLevel.easy;
  
  @override
  void initState() {
    super.initState();
    _initializeAnimations();
    _initializeData();
  }
  
  void _initializeAnimations() {
    _fadeController = AnimationController(
      duration: const Duration(milliseconds: 800),
      vsync: this,
    );
    
    _slideController = AnimationController(
      duration: const Duration(milliseconds: 600),
      vsync: this,
    );
    
    _fadeAnimation = Tween<double>(
      begin: 0.0,
      end: 1.0,
    ).animate(CurvedAnimation(
      parent: _fadeController,
      curve: Curves.easeInOut,
    ));
    
    _slideAnimation = Tween<Offset>(
      begin: const Offset(0, 0.5),
      end: Offset.zero,
    ).animate(CurvedAnimation(
      parent: _slideController,
      curve: Curves.elasticOut,
    ));
    
    // 启动动画
    _fadeController.forward();
    Future.delayed(const Duration(milliseconds: 200), () {
      _slideController.forward();
    });
  }
  
  Future<void> _initializeData() async {
    try {
      await _imageRepository.initialize();
      
      // 设置默认选中的图片
      final images = _imageRepository.getAllImages();
      if (images.isNotEmpty) {
        setState(() {
          _selectedImagePath = images.first.path;
        });
      }
    } catch (e) {
      debugPrint('主页初始化失败: $e');
    }
  }
  
  @override
  Widget build(BuildContext context) {
    final theme = Theme.of(context);
    final screenSize = MediaQuery.of(context).size;
    
    return Scaffold(
      backgroundColor: theme.colorScheme.surface,
      body: SafeArea(
        child: FadeTransition(
          opacity: _fadeAnimation,
          child: SlideTransition(
            position: _slideAnimation,
            child: _buildMainContent(context, screenSize),
          ),
        ),
      ),
    );
  }
  
  Widget _buildMainContent(BuildContext context, Size screenSize) {
    return SingleChildScrollView(
      padding: AppConstants.largePadding,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          const SizedBox(height: 20),
          
          // 应用标题
          _buildAppTitle(context),
          
          const SizedBox(height: 40),
          
          // 游戏预览
          _buildGamePreview(context),
          
          const SizedBox(height: 30),
          
          // 图片选择器
          _buildImageSelector(context),
          
          const SizedBox(height: 30),
          
          // 难度选择器
          _buildDifficultySelector(context),
          
          const SizedBox(height: 40),
          
          // 开始游戏按钮
          _buildStartGameButton(context),
          
          const SizedBox(height: 30),
          
          // 快捷功能按钮
          _buildQuickActions(context),
          
          const SizedBox(height: 20),
        ],
      ),
    );
  }
  
  /// 应用标题
  Widget _buildAppTitle(BuildContext context) {
    final theme = Theme.of(context);
    
    return Column(
      children: [
        Icon(
          Icons.extension,
          size: 64,
          color: theme.colorScheme.primary,
        ),
        const SizedBox(height: 16),
        Text(
          AppConstants.appName,
          style: theme.textTheme.headlineLarge?.copyWith(
            color: theme.colorScheme.primary,
            fontWeight: FontWeight.bold,
          ),
        ),
        const SizedBox(height: 8),
        Text(
          '享受拼图的乐趣',
          style: theme.textTheme.bodyMedium?.copyWith(
            color: theme.colorScheme.onSurface.withValues(alpha: 0.7),
          ),
        ),
      ],
    );
  }
  
  /// 游戏预览
  Widget _buildGamePreview(BuildContext context) {
    if (_selectedImagePath == null) {
      return Container(
        width: 200,
        height: 200,
        decoration: BoxDecoration(
          color: Colors.grey.shade300,
          borderRadius: AppConstants.defaultBorderRadius,
        ),
        child: const Center(
          child: CircularProgressIndicator(),
        ),
      );
    }
    
    return Container(
      width: 200,
      height: 200,
      decoration: BoxDecoration(
        borderRadius: AppConstants.defaultBorderRadius,
        boxShadow: [
          BoxShadow(
            color: Colors.black.withValues(alpha: 0.1),
            blurRadius: 10,
            offset: const Offset(0, 5),
          ),
        ],
      ),
      child: ClipRRect(
        borderRadius: AppConstants.defaultBorderRadius,
        child: Image.asset(
          _selectedImagePath!,
          fit: BoxFit.cover,
          errorBuilder: (context, error, stackTrace) {
            return Container(
              color: Colors.grey.shade200,
              child: Icon(
                Icons.image_not_supported,
                color: Colors.grey.shade500,
                size: 48,
              ),
            );
          },
        ),
      ),
    );
  }
  
  /// 图片选择器 - 修复版本
Widget _buildImageSelector(BuildContext context) {
  final theme = Theme.of(context);
  final images = _imageRepository.getAllImages();
  
  return Column(
    crossAxisAlignment: CrossAxisAlignment.start,
    children: [
      Padding(
        padding: const EdgeInsets.only(left: 8.0),
        child: Text(
          '选择图片 (当前选中: ${_selectedImagePath?.split('/').last ?? '无'})',
          style: theme.textTheme.titleMedium?.copyWith(
            fontWeight: FontWeight.w600,
          ),
        ),
      ),
      const SizedBox(height: 12),
      
      // 简化的图片网格
      if (images.isNotEmpty)
        SizedBox(
          height: 300, // 固定高度，确保可见
          child: GridView.builder(
            shrinkWrap: true,
            physics: const ScrollPhysics(), // 允许滚动
            gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
              crossAxisCount: 3,
              crossAxisSpacing: 8,
              mainAxisSpacing: 8,
              childAspectRatio: 1.0,
            ),
            itemCount: images.length,
            itemBuilder: (context, index) {
              final image = images[index];
              final isSelected = _selectedImagePath == image.path;
              
              return Material( // 添加 Material 以确保点击效果
                color: Colors.transparent,
                child: InkWell( // 使用 InkWell 替代 GestureDetector 以获得更好的点击反馈
                  onTap: () {
                    print('点击了图片: ${image.path}'); // 添加调试信息
                    setState(() {
                      _selectedImagePath = image.path;
                    });
                  },
                  borderRadius: AppConstants.defaultBorderRadius,
                  child: Container(
                    decoration: BoxDecoration(
                      borderRadius: AppConstants.defaultBorderRadius,
                      border: Border.all(
                        color: isSelected 
                            ? theme.colorScheme.primary 
                            : Colors.grey.shade300,
                        width: isSelected ? 4 : 2, // 增加边框宽度使选中效果更明显
                      ),
                      boxShadow: isSelected ? [
                        BoxShadow(
                          color: theme.colorScheme.primary.withValues(alpha: 0.3),
                          blurRadius: 8,
                          offset: const Offset(0, 2),
                        ),
                      ] : null,
                    ),
                    child: ClipRRect(
                      borderRadius: AppConstants.defaultBorderRadius,
                      child: Stack(
                        fit: StackFit.expand,
                        children: [
                          Image.asset(
                            image.path,
                            fit: BoxFit.cover,
                            errorBuilder: (context, error, stackTrace) {
                              print('图片加载失败: ${image.path}, 错误: $error'); // 调试信息
                              return Container(
                                color: Colors.grey.shade200,
                                child: Icon(
                                  Icons.broken_image,
                                  color: Colors.grey.shade400,
                                  size: 32,
                                ),
                              );
                            },
                          ),
                          
                          if (isSelected) ...[
                            Container(
                              color: theme.colorScheme.primary.withValues(alpha: 0.3),
                            ),
                            const Positioned(
                              top: 8,
                              right: 8,
                              child: Icon(
                                Icons.check_circle,
                                color: Colors.white,
                                size: 32, // 增大图标尺寸
                                shadows: [
                                  Shadow(
                                    color: Colors.black54,
                                    offset: Offset(1, 1),
                                    blurRadius: 2,
                                  ),
                                ],
                              ),
                            ),
                            // 添加选中文字提示
                            Positioned(
                              bottom: 8,
                              left: 8,
                              right: 8,
                              child: Container(
                                padding: const EdgeInsets.symmetric(
                                  horizontal: 8,
                                  vertical: 4,
                                ),
                                decoration: const BoxDecoration(
                                  color: Colors.white,
                                  borderRadius: BorderRadius.all(Radius.circular(4)),
                                ),
                                child: const Text(
                                  '已选中',
                                  style: TextStyle(
                                    fontSize: 12,
                                    fontWeight: FontWeight.bold,
                                    color: Colors.blue,
                                  ),
                                  textAlign: TextAlign.center,
                                ),
                              ),
                            ),
                          ],
                        ],
                      ),
                    ),
                  ),
                ),
              );
            },
          ),
        )
      else
        Container(
          height: 150,
          decoration: BoxDecoration(
            color: Colors.grey.shade100,
            borderRadius: AppConstants.defaultBorderRadius,
          ),
          child: Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Icon(
                  Icons.image_not_supported,
                  size: 48,
                  color: Colors.grey.shade400,
                ),
                const SizedBox(height: 8),
                Text(
                  '暂无可用图片',
                  style: TextStyle(
                    color: Colors.grey.shade600,
                    fontSize: 14,
                  ),
                ),
                const SizedBox(height: 4),
                Text(
                  '图片数量: ${images.length}', // 调试信息
                  style: TextStyle(
                    color: Colors.grey.shade500,
                    fontSize: 12,
                  ),
                ),
              ],
            ),
          ),
        ),
    ],
  );
}

  
  /// 难度选择器
  Widget _buildDifficultySelector(BuildContext context) {
    final theme = Theme.of(context);
    
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Padding(
          padding: const EdgeInsets.only(left: 8.0),
          child: Text(
            '选择难度',
            style: theme.textTheme.titleMedium?.copyWith(
              fontWeight: FontWeight.w600,
            ),
          ),
        ),
        const SizedBox(height: 12),
        Wrap(
          spacing: 12,
          runSpacing: 8,
          children: DifficultyLevel.values.map((difficulty) {
            final isSelected = _selectedDifficulty == difficulty;
            
            return GestureDetector(
              onTap: () {
                setState(() {
                  _selectedDifficulty = difficulty;
                });
              },
              child: AnimatedContainer(
                duration: AppConstants.defaultAnimationDuration,
                padding: const EdgeInsets.symmetric(
                  horizontal: 16,
                  vertical: 12,
                ),
                decoration: BoxDecoration(
                  color: isSelected 
                      ? difficulty.color 
                      : theme.colorScheme.surface,
                  borderRadius: AppConstants.defaultBorderRadius,
                  border: Border.all(
                    color: isSelected 
                        ? difficulty.color 
                        : theme.colorScheme.outline,
                    width: isSelected ? 2 : 1,
                  ),
                ),
                child: Row(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Icon(
                      Icons.grid_3x3,
                      size: 16,
                      color: isSelected 
                          ? Colors.white 
                          : theme.colorScheme.onSurface,
                    ),
                    const SizedBox(width: 8),
                    Text(
                      '${difficulty.displayName} (${difficulty.gridSize}x${difficulty.gridSize})',
                      style: theme.textTheme.bodyMedium?.copyWith(
                        color: isSelected 
                            ? Colors.white 
                            : theme.colorScheme.onSurface,
                        fontWeight: isSelected 
                            ? FontWeight.w600 
                            : FontWeight.normal,
                      ),
                    ),
                  ],
                ),
              ),
            );
          }).toList(),
        ),
      ],
    );
  }
  
  /// 开始游戏按钮
  Widget _buildStartGameButton(BuildContext context) {
    final theme = Theme.of(context);
    final canStart = _selectedImagePath != null;
    
    return SizedBox(
      width: double.infinity,
      height: 56,
      child: ElevatedButton(
        onPressed: canStart ? _startGame : null,
        style: ElevatedButton.styleFrom(
          backgroundColor: theme.colorScheme.primary,
          foregroundColor: Colors.white,
          elevation: canStart ? 4 : 0,
          shape: const RoundedRectangleBorder(
            borderRadius: AppConstants.defaultBorderRadius,
          ),
        ),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(
              canStart ? Icons.play_arrow : Icons.image_not_supported,
              size: 24,
            ),
            const SizedBox(width: 8),
            Text(
              canStart ? '开始游戏' : '请选择图片',
              style: const TextStyle(
                fontSize: 18,
                fontWeight: FontWeight.w600,
              ),
            ),
          ],
        ),
      ),
    );
  }
  
  /// 快捷功能按钮
  Widget _buildQuickActions(BuildContext context) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
      children: [
        // 设置按钮（V2.0预留）
        _buildQuickActionButton(
          context,
          icon: Icons.settings,
          label: '设置',
          onTap: () {
            ScaffoldMessenger.of(context).showSnackBar(
              const SnackBar(content: Text('设置功能即将上线！')),
            );
          },
        ),
        
        // 排行榜按钮（V2.0预留）
        _buildQuickActionButton(
          context,
          icon: Icons.leaderboard,
          label: '排行榜',
          onTap: () {
            ScaffoldMessenger.of(context).showSnackBar(
              const SnackBar(content: Text('排行榜功能即将上线！')),
            );
          },
        ),
        
        // 帮助按钮
        _buildQuickActionButton(
          context,
          icon: Icons.help_outline,
          label: '帮助',
          onTap: () => _showHelpDialog(context),
        ),
      ],
    );
  }
  
  Widget _buildQuickActionButton(
    BuildContext context, {
    required IconData icon,
    required String label,
    required VoidCallback onTap,
  }) {
    final theme = Theme.of(context);
    
    return GestureDetector(
      onTap: onTap,
      child: Container(
        padding: const EdgeInsets.symmetric(
          horizontal: 16,
          vertical: 12,
        ),
        decoration: BoxDecoration(
          color: theme.colorScheme.surface,
          borderRadius: AppConstants.defaultBorderRadius,
          border: Border.all(
            color: theme.colorScheme.outline.withValues(alpha: 0.5),
          ),
        ),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Icon(
              icon,
              size: 24,
              color: theme.colorScheme.primary,
            ),
            const SizedBox(height: 4),
            Text(
              label,
              style: theme.textTheme.bodySmall?.copyWith(
                color: theme.colorScheme.onSurface,
              ),
            ),
          ],
        ),
      ),
    );
  }

  /// 开始游戏
void _startGame() {
  if (_selectedImagePath == null) return;
  
  print('=== 开始游戏调试信息 ===');
  print('选中的图片路径: $_selectedImagePath');
  print('选中的难度: $_selectedDifficulty');
  print('========================');
  
  Routes.toGameScreen(
    context,
    imagePath: _selectedImagePath!,
    difficulty: _selectedDifficulty,
  );
}

  

  /// 显示帮助对话框
  void _showHelpDialog(BuildContext context) {
  showDialog(
    context: context,
    builder: (context) => AlertDialog( // 移除const，因为actions中有动态回调
      title: const Text('游戏帮助'),
      content: const SingleChildScrollView(
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          mainAxisSize: MainAxisSize.min,
          children: [
            Text('🎯 游戏目标', style: TextStyle(fontWeight: FontWeight.bold)),
            SizedBox(height: 8),
            Text('将散落的拼图块拖拽到正确位置，完成完整的图片。'),
            SizedBox(height: 16),
            
            Text('🎮 操作方式', style: TextStyle(fontWeight: FontWeight.bold)),
            SizedBox(height: 8),
            Text('• 拖拽拼图块到目标位置'),
            Text('• 拼图块接近正确位置时会自动吸附'),
            Text('• 完成所有拼图块即可获胜'),
            SizedBox(height: 16),
            
            Text('⚙️ 难度说明', style: TextStyle(fontWeight: FontWeight.bold)),
            SizedBox(height: 8),
            Text('• 简单：3x3 = 9块'),
            Text('• 普通：4x4 = 16块'),
            Text('• 困难：5x5 = 25块'),
            Text('• 专家：6x6 = 36块'),
          ],
        ),
      ),
      actions: [
        TextButton(
          onPressed: () => Navigator.pop(context), // 修复：提供正确的回调函数
          child: const Text('我知道了'),
        ),
      ],
    ),
  );
}

  
  @override
  void dispose() {
    _fadeController.dispose();
    _slideController.dispose();
    super.dispose();
  }
}
